package de.rosstauscher.jculfw;

import java.util.ArrayList;
import java.util.List;

/**********************************************************
 * This implementation of the IRawMessageProcessor can be used
 * to build a chain of responsibility to register a list of listeners
 * the data will be passed from one listener to the next until
 * one has processed the data.
 *  
 * @author Rossi java@rosstauscher.de
 *********************************************************/

public class ChainMessageProcessor implements IRawMessageProcessor {

	private List<IRawMessageProcessor> chain; 
	
	/**********************************************************
	 * Constructor
	 *********************************************************/
	
	public ChainMessageProcessor() {
		super();
		this.chain = new ArrayList<IRawMessageProcessor>();
	}
	
	/**********************************************************
	 * Register a new listener in the chain.
	 * @param p the processor to add.
	 * @return true if it was registered, false if it was already there.
	 *********************************************************/
	
	public boolean addProcessor(IRawMessageProcessor p) {
		return this.chain.add(p);
	}
	
	/**********************************************************
	 * Removes a previously registered listener.
	 * @param p the processor to remove.
	 * @return true if removed, false if it was not registered.
	 *********************************************************/
	
	public boolean removeProcessor(IRawMessageProcessor p) {
		return this.chain.remove(p);
	}

	/**********************************************************
	 * This will do the parsing work.
	 * @see de.rosstauscher.jculfw.IRawMessageProcessor#parseInput(java.lang.String)
	 * @param data to process.
	 * @return true if the data was processed by one of the listeners else false.
	 *********************************************************/

	public boolean parseInput(String data) {
		for (IRawMessageProcessor p : this.chain) {
			if (p.parseInput(data)) {
				return true;
			}
		}
		return false;
	}

}
